export default function loading(config) {
    this.id = config.id
    this.flag = config.flag
    this.canvas = document.getElementById(this.id);
    this.context = this.canvas.getContext("2d");
    this.conterX = this.canvas.width / 2;
    this.conterY = this.canvas.height / 2;
    this.rad = Math.PI * 2 / 100;
    this.oneSpeed = 0.2;
    this.twoSpeed = 0.1
    this.threeSpeed = 6
    this.radSpeed = Math.PI * 2 / 100
    this.progress = 0
    if(window.progress){
        this.progress=window.progress
    }
    
    this.Initdraw()
}

loading.prototype.Initdraw = function () {
    if (window.requestAnimationFrame) {
        this.draw()
        window.requestAnimationFrame(this.Initdraw.bind(this));
    } else {
        setInterval(() => {
            this.draw()
        }, 1000/30);
    }
}


loading.prototype.draw = function () {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.widthCricle();
    this.text();
    this.blueCricle();
    if(this.flag){
        this.progress+= 10
        if (this.progress > 100) {
        this.progress =100
        }
        return
    }
    if (this.progress >= 0 && this.progress < 20) {
        this.progress += this.oneSpeed;
    } else if (this.progress > 20 && this.progress < 95) {
        this.progress += this.threeSpeed;
    } else if (this.progress > 95&&this.progress <99) {
        this.progress += this.twoSpeed;
    }

    window.progress=this.progress
    if (this.progress > 100) {
        // this.progress = 0
        window.progress=null
    }
}
loading.prototype.blueCricle = function () {
    this.context.save();
    this.context.beginPath();
    this.context.strokeStyle = "#49f";
    this.context.lineWidth = 8;
    this.context.arc(this.conterX, this.conterY, 100, -Math.PI / 2, -Math.PI / 2 + this.progress * this.rad,
        false);
    this.context.stroke();
    this.context.closePath();
    this.context.restore()
}

loading.prototype.widthCricle = function () {
    this.context.save();
    this.context.beginPath();
    this.context.strokeStyle = "red";
    this.context.arc(this.conterX, this.conterY, 100, 0, Math.PI * 2, false);
    this.context.stroke();
    this.context.closePath();
    this.context.restore();
}
loading.prototype.text = function () {
    this.context.save();
    this.context.strokeStyle = "#49f";
    this.context.font = "20px Arial";
    this.context.strokeText(this.progress.toFixed(0) + "%", this.conterX - 25, this.conterY + 10);
    this.context.stroke();
    this.context.restore();
}